<script setup lang="ts">
import { reactive, ref, type ComponentPublicInstance } from "vue"
import { getListByUidApi as getListApi } from "@/api/electron"
import { type FormInstance } from "element-plus"
import { Search, Refresh, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import Tables from "./table.vue"
import Decimal from "decimal.js"
import { sumValues } from "@/utils/common"

const pictureRef = ref<ComponentPublicInstance<InstanceType<typeof Tables>> | null>(null)
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #region 打开对话框
const dialogVisible = ref(false)

const showClick = (el: any) => {
  console.log(el)
  uid.value = el.uid
  paginationData.currentPage = 1
  handleSearch()
  dialogVisible.value = true
}

defineExpose({ showClick })
// #endregion

// #region dialog 对话框关闭前操作
const handleClose = () => {
  dialogVisible.value = false
  emit("DialogClose", true)
}
const emit = defineEmits(["DialogClose"])
// #endregion

//#region 查
const uid = ref<number>(0)
const tableData = ref<any[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  title: "",
  phone: ""
})
const getTableData = () => {
  loading.value = true
  getListApi({
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    uid: uid.value,
    ...searchData
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

// #region 列表数据变化
const total = reactive({
  acceptor: "",
  billAmount: "",
  points: "",
  open: "",
  rebate: "",
  interestDeduction: ""
})
// 重置total
const resetTotal = () => {
  total.acceptor = ""
  total.billAmount = ""
  total.points = ""
  total.open = ""
  total.rebate = ""
  total.interestDeduction = ""
}

const onTotal = () => {
  resetTotal()
  if (discountLen.value > 0 && buysLen.value == 0) {
    const { billAmount, interestDeduction } = sumValues(discountList.value)
    discountTotal.billAmount = billAmount
    discountTotal.interestDeduction = interestDeduction
    total.acceptor = "合计"
    total.billAmount = discountTotal.billAmount + "元"
    total.points = "贴息费"
    total.interestDeduction = discountTotal.interestDeduction + "元"
  } else if (buysLen.value > 0 && discountLen.value == 0) {
    const { billAmount, rebate } = sumValues(buysList.value)
    buyTotal.billAmount = billAmount
    buyTotal.rebate = rebate
    total.billAmount = buyTotal.billAmount + "元"
    total.acceptor = "合计"
    total.points = "返点"
    total.interestDeduction = buyTotal.rebate + "元"
  } else if (buysLen.value > 0 && discountLen.value > 0) {
    const totalDis = sumValues(discountList.value)
    discountTotal.billAmount = totalDis.billAmount
    discountTotal.interestDeduction = totalDis.interestDeduction
    const totalBuy = sumValues(buysList.value)
    buyTotal.billAmount = totalBuy.billAmount
    buyTotal.rebate = totalBuy.rebate

    const billAmountDis = new Decimal(discountTotal.billAmount || 0)
    const billAmountBuy = new Decimal(buyTotal.billAmount || 0)
    const number = billAmountDis.sub(billAmountBuy).toNumber()
    if (number == 0) {
      total.billAmount = "已走平"
    } else if (number > 0) {
      total.acceptor = "票面差额"
      total.billAmount = number + "元"
    } else {
      total.acceptor = "票面差额"
      total.billAmount = number + "元"
    }

    const discount = new Decimal(discountTotal.interestDeduction || 0)
    const buy = new Decimal(buyTotal.rebate || 0)
    const difference = discount.sub(buy).toNumber()
    if (difference == 0) {
      total.interestDeduction = "已走平"
    } else if (difference > 0) {
      total.points = "贴息费"
      total.interestDeduction = difference + "元"
    } else {
      total.points = "返点"
      total.interestDeduction = difference + "元"
    }
  }

  total.billAmount = total.billAmount.replace("-", "")
  total.interestDeduction = total.interestDeduction.replace("-", "")
  total.rebate = total.rebate.replace("-", "")
}
// #endregion

const pictureFun = (item: any) => {
  console.log(item)
  const hisObj = JSON.parse(item.text)
  discountList.value = hisObj.discount
  discountLen.value = discountList.value.length
  buysList.value = hisObj.buy
  buysLen.value = buysList.value.length
  console.log(hisObj)
  onTotal()
  if (pictureRef.value) {
    pictureRef.value.showClick({
      discountLen: hisObj.discount.length,
      buysLen: hisObj.buy.length,
      discountList: hisObj.discount,
      buysList: hisObj.buy,
      total: total,
      discountTotal: discountTotal,
      specialNum: specialNum.value,
      special: special.value,
      items: item
    })
  }
}

const buysList = ref<any[]>([])
const buysLen = ref<number>(0)
const discountList = ref<any[]>([])
const discountLen = ref<number>(0)
const discountTotal = reactive({
  serialNumber: "",
  matter: "",
  acceptor: "",
  billAmount: "",
  points: "",
  open: "",
  rebate: "",
  interestDeduction: ""
})
const buyTotal = reactive({
  serialNumber: "",
  matter: "",
  acceptor: "",
  billAmount: "",
  points: "",
  open: "",
  rebate: "",
  interestDeduction: ""
})
const special = ref<boolean>(false)
const specialNum = ref<number>(0)
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="列表"
    width="50%"
    :before-close="handleClose"
    destroy-on-close
    draggable
    fullscreen
  >
    <div>
      <div class="app-container">
        <el-card v-loading="loading" shadow="hover" class="search-wrapper">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="title" label="企业名称">
              <el-input v-model="searchData.title" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-loading="loading" shadow="hover">
          <div class="toolbar-wrapper">
            <div>&nbsp;</div>
            <div>
              <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
              <el-tooltip content="刷新当前页">
                <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
              </el-tooltip>
            </div>
          </div>
          <div class="table-wrapper">
            <el-table :data="tableData">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column prop="title" label="企业名称" align="center" />
              <el-table-column prop="create_time" label="创建时间" align="center" />
              <el-table-column fixed="right" label="操作" width="150" align="center">
                <template #default="scope">
                  <el-button type="primary" text bg size="small" @click="pictureFun(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pager-wrapper">
            <el-pagination
              background
              :layout="paginationData.layout"
              :page-sizes="paginationData.pageSizes"
              :total="paginationData.total"
              :page-size="paginationData.pageSize"
              :currentPage="paginationData.currentPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
      <Tables ref="pictureRef" />
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
